{% extends 'layout.html' %}
{% load mytags %}

{% block content %}
    <div class="row">
        <div class="col-md-12">
            <div class="box">
                <div class="box-header with-border">
                    <h3 class="box-title">查看资产</h3>

                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i
                                class="fa fa-chevron-up"></i>
                        </button>
                        <div class="btn-group">
                            <button type="button" class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown">
                                <i class="fa fa-wrench"></i></button>
                            <ul class="dropdown-menu" role="menu">
                                <li><a href="#">Action</a></li>
                                <li><a href="#">Another action</a></li>
                                <li><a href="#">Something else here</a></li>
                                <li class="divider"></li>
                                <li><a href="#">Separated link</a></li>
                            </ul>
                        </div>
                        <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="table-responsive">
                        <div id="toolbar">
                            <a href="{% url 'asset_add' %}" class="btn btn-sm btn-default">
                                <i class="fa fa-plus"></i> 添加
                            </a>
                            <button id="btn_remove" class="btn btn-sm btn-danger">
                                <i class="fa fa-trash-o"></i> 批量删除
                            </button>
                            <button id="exec_cmd" name="exec_cmd" class="btn btn-sm btn-info">
                                <i class="fa fa-terminal"></i> 执行命令
                            </button>
                            <button id="btn_flush" class="btn btn-sm btn-success">
                                <!--<i class="fa fa-spin fa-refresh"></i> 更新资产-->
                                <i class="fa fa-refresh"></i> 更新资产
                            </button>
                            <div class="btn-group">
                                <button type="button" class="btn btn-sm btn-primary dropdown-toggle"
                                        data-toggle="dropdown">
                                    <i class="fa fa-bars"></i> 更多 <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu" role="menu">
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-television"></i>
                                            <span class="text">终端</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-reply"></i>
                                            <span class="text">重启</span>
                                        </a>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-power-off"></i>
                                            <span class="text">关机</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-key"></i>
                                            <span class="text">加载SSH秘钥</span>
                                        </a>
                                    <li class="divider"></li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-plus"></i>
                                            <span class="text">添加到资源组</span>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                            <form id="search_form" style="display: inline-block;">
                                <label>
                                    <select name="idc" class="form-control m-b input-sm" onchange="change_info()">
                                        <option value="">机房</option>
                                        {% for idc in idc_all %}
                                            {% ifequal idc.name idc_name %}
                                                <option value="{{ idc.name }}"
                                                        selected> {{ idc.name|slice:":20" }}</option>
                                            {% else %}
                                                <option value="{{ idc.name }}"> {{ idc.name|slice:":20" }}</option>
                                            {% endifequal %}
                                        {% endfor %}
                                    </select>
                                </label>
                                <label>
                                    <select name="group" class="form-control m-b input-sm" onchange="change_info()">
                                        <option value="">主机组</option>
                                        {% for asset_group in asset_group_all %}
                                            {% ifequal asset_group.name group_name %}
                                                <option value="{{ asset_group.name }}"
                                                        selected> {{ asset_group.name|slice:":20" }} </option>
                                            {% else %}
                                                <option value="{{ asset_group.name }}"> {{ asset_group.name|slice:":20" }} </option>
                                            {% endifequal %}
                                        {% endfor %}
                                    </select>
                                </label>
                                <label>
                                    <select name="asset_type" class="form-control m-b input-sm"
                                            onchange="change_info()">
                                        <option value="">资产类型</option>
                                        {% for t in asset_types %}
                                            {% ifequal t.0|int2str type %}
                                                <option value="{{ t.0 }}" selected> {{ t.1 }}</option>
                                            {% else %}
                                                <option value="{{ t.0 }}"> {{ t.1 }}</option>
                                            {% endifequal %}
                                        {% endfor %}
                                    </select>
                                </label>
                                <label>
                                    <select name="status" class="form-control m-b input-sm" onchange="change_info()">
                                        <option value="">资产状态</option>
                                        {% for s in asset_status %}
                                            {% ifequal s.0|int2str status %}
                                                <option value="{{ s.0 }}" selected> {{ s.1 }}</option>
                                            {% else %}
                                                <option value="{{ s.0 }}"> {{ s.1 }}</option>
                                            {% endifequal %}
                                        {% endfor %}
                                    </select>
                                </label>
                            </form>
                        </div>
                        <table id="table">
                        </table>
                    </div>
                    <!-- /.row -->
                </div>
                <!-- ./box-body -->
                <div class="box-footer">
                    <div class="row">

                    </div>
                    <!-- /.row -->
                </div>
                <!-- /.box-footer -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- context menu -->
    <ul id="context-menu" class="dropdown-menu context-menu">
        <li data-item="poweroff"><a><i class="fa fa-stop"></i> 关机</a></li>
        <li data-item="restart"><a><i class="fa fa-circle-o-notch"></i> 重启</a></li>
        <li data-item="connect"><a><i class="fa fa-bolt"> </i> 连接</a></li>
        <li data-item="edit"><a><i class="fa fa-pencil"></i> 修改</a></li>
        <li data-item="addtogroup"><a><i class="fa fa-plus"></i> 添加到资源组</a></li>
        <li data-item="delete"><a><i class="fa fa-trash"></i> 删除</a></li>
    </ul>
{% endblock %}

{% block self_footer_js %}
    <script src="/static/plugins/bootstrap-table/extensions/contextmenu/bootstrap-table-contextmenu.min.js"></script>
    <script>
        var $table = $('#table');
        function initTable() {
            $table.bootstrapTable({
                //绑定右键菜单
                contextMenu: '#context-menu',
                onContextMenuItem: function (row, $el) {
                    if ($el.data("item") == "edit") {
                        alert("Edit: " + row.id + ' ' + row.hostname);
                    } else if ($el.data("item") == "delete") {
                        alert("Delete: " + row.id + ' ' + row.hostname);
                    } else if ($el.data("item") == "action1") {
                        alert("Action1: " + row.id + ' ' + row.hostname);
                    } else if ($el.data("item") == "action2") {
                        alert("Action2: " + row.id + ' ' + row.hostname);
                    }
                },
                method: 'get',
                url: '{% url 'asset_getlist' %}',
                toolbar: '#toolbar',
                idField: 'id',
                sidePagination: "server",
                striped: true,
                search: true,
                showRefresh: true,
                showExport: true,
                exportDataType: 'basic',
                exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel'],
                pagination: true,
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                cache: false,
                clickToSelect: true,
                columns: [
                    {
                        field: 'state',
                        checkbox: true,
                        align: 'center'
                    }, {
                        field: 'id',
                        title: 'ID',
                        align: 'center',
                        visible: false
                    }, {
                        field: 'hostname',
                        title: '主机名',
                        sortable: true,
                        align: 'center',
                        formatter: hostnameFormatter
                    }, {
                        field: 'ip',
                        title: 'IP',
                        align: 'center'
                    }, {
                        field: 'idc',
                        title: 'IDC',
                        align: 'center'
                    }, {
                        field: 'group',
                        title: '所属组',
                        align: 'center'
                    }, {
                        field: 'os',
                        title: '操作系统',
                        align: 'center'
                    }, {
                        field: 'cpu_num',
                        title: 'CPU核数',
                        align: 'center'
                    }, {
                        field: 'memory',
                        title: '内存',
                        align: 'center'
                    }, {
                        field: 'online-status',
                        title: '在线状态',
                        align: 'center',
                        formatter: statusFormatter
                    }, {
                        field: 'operate',
                        title: '操作',
                        align: 'center',
                        events: operateEvents,
                        formatter: operateFormatter
                    }
                ]
            })
        }

        function hostnameFormatter(value, row, index) {
            return [
                '<a href="{% url 'asset_detail' %}?id=' + row.id + '">',
                value + '</a>  ',
                '<a href="javascript:terminal(' + row.id + ')" data-toggle="tooltip" title="Web 终端"><span class="blue"><i class="fa fa-laptop"></i></span></a>'
            ].join('');
        }

        //操作列方法
        function operateFormatter(value, row, index) {
            return [
                '<a class="btn btn-xs btn-default" href="{% url 'asset_edit' %}?id=' + row.id + '">',
                '<i class="fa fa-edit"></i> 编辑</a> ',
                //'<a class="conn btn btn-xs btn-success" href="javascript:void(0)">',
                //'<i class="fa fa-flash"></i> 连接</a> ',
                '<a class="remove btn btn-xs btn-danger" href="javascript:void(0)" title="Remove">',
                '<i class="fa fa-trash-o"></i> 删除</a>',
            ].join('');
        }

        function statusFormatter(value, row, index) {
            return '<span class="text-success"><span class="icon-status icon-running"></span>&nbsp; 运行中</span>'
            //return '<span class="running"><i class="fa fa-circle text-success"></i> 运行中</span>'
            //<span class="stop"><span class="icon-status icon-stopped"></span>&nbsp; 已关机</span>
        }

        window.operateEvents = {
            'click .edit': function (e, value, row, index) {
                //alert('You click like action, row: ' + JSON.stringify(row));
                //Edit(row.id);
                //alert(row.id);
                location.href = '{% url 'asset_edit' %}?id=' + row.id;
            },
            'click .remove': function (e, value, row, index) {
                $table.bootstrapTable('remove', {
                    field: 'id',
                    values: [row.id]
                });
            },
            'click .conn': function (e, value, row, index) {
                //window.open('/terminal', '_blank')
                {#                window.open('/terminal?instance_id=' + row.id, '', 'location=no, resizeable=no, height=600, width=800,toolbar=no,menubar=no,scrollbars=auto,status=no');#}
                terminal(row.id);
            },
        };

        function terminal(instance_id) {
            window.open('/terminal?instance_id=' + instance_id + "&zone=cd", '', 'location=no, resizeable=no, height=600, width=800,toolbar=no,menubar=no,scrollbars=auto,status=no');
        }

        function change_info() {
            var args = $("#search_form").serialize();
            console.log(args)
        }

        $(function () {
            initTable();
            //todo:tooltip
            //$("[data-toggle='tooltip']").tooltip();

            // update asset info
            $("#btn_flush").click(function () {
                //$("#btn_flush").text('更新中...');
                //$("#btn_flush i").addClass('fa-spin');
                $("#btn_flush").html('<i class="fa fa-spin fa-refresh"></i> 更新中...');
                $.ajax({
                    url: '{% url 'get_server_info' %}?action=flush',
                    type: 'POST',
                    data: {},
                    //url返回的值
                    success: function (data) {
                        var ret = jQuery.parseJSON(data);
                        //console.log(obj.status);
                        //console.log(data);
                        //console.log(data.status);
                        if (ret.status == 'ok') {
                            //重新加载表格
                            $table.bootstrapTable("refresh");
                            $("#btn_flush").html('<i class="fa fa-refresh"></i> 更新资产');
                        }

                    },
                    error: function () {
                        console.log('failed')
                    }
                });
            });

            //delete button
            $("#btn_remove").click(function () {
                var selected = $table.bootstrapTable('getSelections');
                if ($(selected).length > 0) {
                    BootstrapDialog.confirm({
                        title: "警告",
                        message: "确定删除选中的" + $(selected).length + "个主机吗？",
                        btnCancelLabel: '放弃',
                        btnCancelClass: 'btn-white',
                        btnOKLabel: '确认',
                        btnOKClass: 'btn-default',
                        callback: function (result) {
                            if (result) {
                                var ids = new Array($(selected).length);
                                $.each(selected, function (index, value) {
                                    ids[index] = value.id;
                                });
                                $.post("{% url 'asset_del' %}", {ids: ids}, function (data) {
                                        if (data.code != 0) {
                                            $table.bootstrapTable("refresh");
                                            dialogItself.close();
                                        }
                                        else BootstrapDialog.alert(data.message);

                                    }, "json"
                                );
                            }
                        }
                    });
                }
                else BootstrapDialog.warning("请选择要删除的行");
            });

        });
    </script>
{% endblock %}